---
import * as mod from 'virtual:astro:assets/fonts/internal';
import { filterPreloads } from 'astro/assets/fonts/runtime';
import { AstroError, AstroErrorData } from '../dist/core/errors/index.js';

// TODO: remove check when fonts are stabilized
const { internalConsumableMap } = mod;
if (!internalConsumableMap) {
	throw new AstroError(AstroErrorData.ExperimentalFontsNotEnabled);
}

interface Props {
	/** The `cssVariable` registered in your Astro configuration. */
	cssVariable: import('astro:assets').CssVariable;
	/** Whether it should output [preload links](https://web.dev/learn/performance/optimize-web-fonts#preload) or not. */
	preload?: import('astro:assets').FontPreloadFilter;
}

const { cssVariable, preload = false } = Astro.props as Props;
const data = internalConsumableMap.get(cssVariable);
if (!data) {
	throw new AstroError({
		...AstroErrorData.FontFamilyNotFound,
		message: AstroErrorData.FontFamilyNotFound.message(cssVariable),
	});
}

const filteredPreloadData = filterPreloads(data.preloadData, preload);
---

<style set:html={data.css}></style>
{
	filteredPreloadData?.map(({ url, type }) => (
		<link rel="preload" href={url} as="font" type={`font/${type}`} crossorigin />
	))
}
